package com.Service;
import com.Dao.GetUserDao;
import com.Dao.Imp.GetUserDaoImp;
import com.Dao.Imp.InsertUserDaoImp;
import com.Dao.InsertUserDao;
import com.Utils.RedisUtil;
import com.common.Result;
import com.pojo.RegisterDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Service
@Slf4j
public class RegistService {
    private final static String REGIS_SMS_CODE_PRE = "REGIS_SMS_CODE:%s";
    @Autowired
    private RedisUtil redisUtil;

    public Result register(RegisterDTO registerDTO) {
        GetUserDao getUserDao = new GetUserDaoImp();
        try {
            //校验手机号账户是否存在 已存在 则提示用户直接登录
            int loginFlag = getUserDao.getUser(registerDTO.getUsername());
            if (1 == loginFlag) {
                return new Result().error(10001,"账户已存在，请前往登陆");
            }
            Object codeCache = redisUtil.get(String.format(REGIS_SMS_CODE_PRE, registerDTO.getUsername()));
            if (ObjectUtils.isEmpty(codeCache) || !registerDTO.getConfirmCode().equals(String.valueOf(codeCache))) {
                return new Result().error("验证码错误或已过期");
            }
            //保存用户信息
            InsertUserDao insertUserDao = new InsertUserDaoImp();
            int insert = insertUserDao.Insert(registerDTO.getUsername(), registerDTO.getPassword());
            if (1==insert){
                //已存在 返回失败
                return new Result().error(10001,"账户已存在，请前往登陆");
            }
            return new Result().ok("success");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("账号注册异常:{}", e.getMessage(), e);
            return new Result().error("账号注册失败");
        }
    }

}
